using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Musicman.Business;
using Musicman.Common.Entities;
using System.Collections.Generic;
using MusicmanWeb.Custom;
using System.Net.Mail;
using Musicman.Utilities;
using System.IO;
using Musicman.Common;

namespace MusicmanWeb.USER
{
    public partial class Helpdesk : MusicmanPage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            ReddirectNonActiveSession();
            UserManager.Instance.UpdateLastWallVisit(Int64.Parse(User.Identity.Name));
            if (!IsPostBack)
            {
                Cache.Remove("firstmsg");
                Cache.Remove("lastmsg");
                List<UserMessage> messages = GetUserMessages(true);
                wallmsgrepeater.DataSource = messages;
                wallmsgrepeater.DataBind();
            }
            profileImg.Src = "ProfilePicture.axd?personid=" + User.Identity.Name;
        }
        
        protected void AddMessage_Command(object sender, CommandEventArgs e)
        {
            User msgSender = UserManager.Instance.GetUser(Int64.Parse(User.Identity.Name));
            UserMessage msg = new UserMessage();
            msg.MessageDate = DateTime.Now;
            msg.Sender = msgSender;
            msg.Message = messagetxt.Value;
            if (UserMassageManager.Instance.InsertMessage(msg))
            {
                Cache.Remove("firstmsg");
                Cache.Remove("lastmsg");
                List<UserMessage> messages = GetUserMessages(true);
                wallmsgrepeater.DataSource = messages;
                wallmsgrepeater.DataBind();
                messagetxt.Value = "";
            }
        }

        protected void Wallmsgrepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            UserMessage msg = e.Item.DataItem as UserMessage;
            UserMessageControl ctrl = (UserMessageControl)e.Item.FindControl("messagecontrol");
            if (msg != null)
            {
                if (ViewState[String.Format("Expand_{0}", msg.MessageID)] != null)
                {
                    ctrl.Expanded = (bool)ViewState[String.Format("Expand_{0}", msg.MessageID)];
                }
                ctrl.Message = msg;
            }
        }

        protected void wallmsgrepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            User user = new User();
            user.Personid = 1;
            List<UserMessage> messages = GetUserMessages(true);
            if (e.CommandName == "Expand")
            {
                ViewState[String.Format("Expand_{0}", e.CommandArgument)] = true;
            }
            wallmsgrepeater.DataSource = messages;
            wallmsgrepeater.DataBind();
            if (e.CommandName == "AddComment" && 
                Boolean.Parse(AppSettingsHelper.GetWebConfigValue(Constants.EmailEnabled)))
            {
                SendNotificationMail(Int64.Parse(e.CommandArgument.ToString()));
            }
        }

        private void SendNotificationMail(long messageID)
        {
            UserMessage message = UserMassageManager.Instance.GetFullMessage(messageID);
            if (message != null)
            {
                long meID = Int64.Parse(User.Identity.Name);
                MailAddress ema = null;
                MailMessage email = new MailMessage();
                
                email.From = new MailAddress("musicmanservices@musicman.com", "Musicman");
                User u = null;
                for (int i = 0; i < message.Commments.Count; i++)
                {
                    u = message.Commments[i].Sender;
                    ema = new MailAddress(u.Emailaddress);
                    if (u.Personid != meID && !email.To.Contains(ema))
                    {
                        email.To.Add(ema);
                    }
                }

                UserMessage comment = message.Commments[message.Commments.Count -1];
                User comentator = comment.Sender;
                u = message.Sender;
                ema = new MailAddress(u.Emailaddress);
                if (u.Personid != meID && !email.To.Contains(ema))
                {
                    email.To.Add(ema);
                }
                string mailTemplate = "";
                using (StreamReader sr = new StreamReader(File.Open(Server.MapPath("..//templates//post_commented.html"), FileMode.Open, FileAccess.Read)))
                {
                    mailTemplate = sr.ReadToEnd();
                }
                email.Subject = String.Format("{0} {1}'s post commented", u.Firstname, u.Lastname);
                email.Body = String.Format(mailTemplate, 
                    comentator.Firstname, 
                    comentator.Lastname, 
                    u.Firstname, 
                    u.Lastname, 
                    message.Message,
                    comment.Message,
                    GetAppServer());
                email.IsBodyHtml = true;
                MailSender.Instance.SendMailAsync(email);
            }

        }

        protected void PageCahnge_Command(object sender, CommandEventArgs e)
        {
            List<UserMessage> messages = null;
            if (e.CommandArgument.ToString() == "prev")
            {
                Cache["lastmsg"] = DateTime.MinValue;
                messages = GetUserMessages(false);
            }
            else if (e.CommandArgument.ToString() == "next")
            {
                Cache["firstmsg"] = DateTime.MinValue;
                messages = GetUserMessages(true);
            }
            wallmsgrepeater.DataSource = messages;
            wallmsgrepeater.DataBind();
        }

        protected List<UserMessage> GetUserMessages(bool next)
        {
            List<UserMessage> messages = null;
            if (Cache["messages"] != null)
            {
                messages = (List<UserMessage>)Cache["messages"];
            }
            else
            {
                DateTime first = (Cache["firstmsg"] != null) ? (DateTime)Cache["firstmsg"] : DateTime.MinValue;
                DateTime last = (Cache["lastmsg"] != null) ? (DateTime)Cache["lastmsg"] : DateTime.MinValue;
                messages = UserMassageManager.Instance.LoadUserMessages(5, next ? last : first, next);
                if (messages.Count != 0)
                {
                    Cache["firstmsg"] = messages[0].MessageDate;
                    Cache["lastmsg"] = messages[messages.Count - 1].MessageDate;
                }
                Cache.Insert("messages", messages,
                        new System.Web.Caching.CacheDependency(new string[] { }, new string[] { "firstmsg", "lastmsg" }),
                        System.Web.Caching.Cache.NoAbsoluteExpiration,
                        new TimeSpan(0, 3, 0));
            }
            return messages;
        }
    }

}
